package com.zhanglijie.improve.aqs.share.countLatch;

import java.security.InvalidParameterException;

import com.zhanglijie.improve.aqs.exclusive.MyAbstractQueuedSynchronizer;
import com.zhanglijie.improve.aqs.share.semaphore.MySemaphore;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/10/5 0005 18:49
 */
public class MyCountDownLatch {
    private final MySync sync;

    /**
     * 无参默认构造方法是 非公平锁
     */
    public MyCountDownLatch(int count) {
        if(count < 0){
            throw new IllegalArgumentException();
        }
        sync = new MySync(count);
    }



     static class MySync extends MyAbstractQueuedSynchronizer {
        public MySync(int count){
            setState(count);
        }
        public int getCount(){
            return getState();
        }

         /**
          * countDownLatch释放锁 由countDownLatch.countDown（）方法触发
          * @param arg
          * @return
          */
        @Override
        protected boolean tryReleaseShared(int arg){
            for(;;){
                int current = getState();
                if(current == 0 ){
                    return false;
                }
                int next = current-arg;

                if(compareAndSetState(current,next)){
                    return next == 0;
                }
            }
        }

         /**
          * 获取锁 往下执行  由countDownLatch.await()触发
          * @param arg
          * @return
          * 返回1 表示获得锁 然后传给下游看看能不能继续唤醒后面的阻塞线程   返回-1表示没获得锁继续阻塞
          */
         @Override
         protected int tryAcquireShared(int arg){
            return getState() == 0?1:-1;
         }

    }


    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    /**
     * 共享锁（不响应中断）
     */
    public void acquireUnInterruptibly(){
        sync.acquireShared(1);
    }


    public void countDown(){
        sync.releaseShared(1);
    }

}
